(function() {
    "use strict";
    window.Sugar = function (act, actid) {

        if (typeof (window.SugarConf) != "undefine") {
            window.SugarConf = {};
        }
        if (typeof (window.SugarTools)!= "undefine") {
            window.SugarTools = {};
        }

        window.SugarConf.sugar = this;

        this.empty = function (val) {
            return val == "" || val == null || val == false || val == 0 || val == '0';
        }

        if (this.empty(window.SugarConf.active) && !this.empty(act)) {
            window.SugarConf.active = act;
        }
        if (this.empty(window.SugarConf.actid) && !this.empty(actid)) {
            window.SugarConf.actid = actid;
        }

        this.getCookie = function (field) {
            var stlist = document.cookie.split(";");
            var once;
            var swaplist;
            for (once in stlist) {
                swaplist = stlist[once].split("=");
                if (swaplist[0].replace(/(^\s+)|(\s+$)/g,"") == field) {
                    return swaplist[1];
                }
            }
            return null;
        }
        this.setCookie = function (name, value, expiredays) {
            var exdate = new Date()
            exdate.setDate(exdate.getDate() + expiredays)
            document.cookie = name + "=" +
                decodeURIComponent(value) +
                ((expiredays == null) ? "" : ";expires=" +
                    exdate.toGMTString());
            return (this.getCookie(name) != null);
        };

        this.cover = function(state) {
            let cover = document.getElementById("sugar-cover");
            if (cover == null) {
                cover = document.createElement("div");
                cover.id = "sugar-cover";
                var cav = document.createElement("div");
                cav.id = "cover-cav";
                cover.appendChild(cav);
                document.body.appendChild(cover);
            }
            if (state === "on") {
                window.SugarConf.coverstate = "on";
                cover.style.display = "block";
            }
            if (state === "off") {
                window.SugarConf.coverstate = "off";
                cover.style.display = "none";
            }
        }

        this.isset = function(val) {
            return ! (typeof(val) === "undefined");
        };

        this.call = function(json) {
            if (this.empty(this.getCookie("Coverid"))) {
                alert("链接已过期，请刷新页面再试");
                return 0;
            }
            
            if (window.XMLHttpRequest)
                var xhr = new XMLHttpRequest();
            else
                var xhr = new ActiveXObject("Microsoft.XMLHTTP");
            if (json.cover) {
                this.cover("on");
            }
            xhr.onerror = function(e) {
                console.log('sugar request failed');
                console.log(e);
            }
            xhr.ontimeout = function() {
                throw new Error('sugar request timeout');
            }
            xhr.onprogress = this.isset(json.progress) ? json.progress : false;
            var dStr = "";
            let datakey;
            for (datakey in json.data) {
                dStr += "&"+ datakey+ "="+ json.data[datakey];
            }
            var method = json.method.toUpperCase();
            if (method == "GET") {
                /**
                 * assembling url params
                 */
                if (json.url.indexOf("?") < 0) {
                    json.url = json.url + "?" + dStr.substr(1) + "$active=" + window.SugarConf.active + "&activeid=" + window.SugarConf.actid;
                } else {
                    json.url = json.url + dStr + "&active=" + window.SugarConf.active + "&activeid=" + window.SugarConf.actid;
                }
            }
            xhr.open(method, json.url, true);
            try {
                xhr.withCredentials = json.withCookie == false ? false : true;
            } catch (e) {
                xhr.withCredentials = false;
            }
            var defaultType = "application/x-www-form-urlencoded;charset=UTF-8";
            xhr.setRequestHeader("Accept", "application/json");
            xhr.setRequestHeader("Content-Type", defaultType);
            xhr.responseType = this.isset(json.type) ? json.type: "text";
            let key;
            for (key in json.headers) {
                xhr.setRequestHeader(key, json.headers[key]);
            }
            if (method == "GET") {
                xhr.send(null);
            } else {
                let subst = dStr + "&active=" + window.SugarConf.active + "&activeid=" + window.SugarConf.actid;
                xhr.send(subst);
            }
            var that = this;
            xhr.onreadystatechange = function() {
                if (xhr.readyState == 4) {
                    if (xhr.status == 200) {
                        if (json.cover) {
                            that.cover("off");
                        }
                        let calldata = that.isset(xhr.response) ? xhr.response : xhr.responseText;
                        json.success(calldata);
                        return 0;
                    }
                }
            }
        };

        this.toolsFactory = {
            infoBox: function(node, config) {
                var sugar = window.SugarConf.sugar;
                if (sugar.getCookie("Coverid") == null) {
                    alert("链接已过期，请刷新页面再试");
                    return 0;
                }
                this.create = function() {
                    var box = '<div id="infoBox-box">\
                                    <div class="infobox-nav">登陆助手</div>\
                                    <input type="text" id="nickname" />\
                                    <input type="password" id="password" />\
                                    <div id="infobox-sub">登 陆</div>\
                                    <div id="infobox-reg">注 册</div>\
                                </div>';
                    node.innerHTML += box;
                    document.body.appendChild(node);
                    var nickname = document.getElementById("nickname");
                    var password = document.getElementById("password");
                    let sub = document.getElementById("infobox-sub");
                    let reg = document.getElementById("infobox-reg");
                    reg.addEventListener("click", function(event) {
                        var nick = nickname.value;
                        var pwd = password.value;
                        if (sugar.empty(nick)) {
                            alert("用户名不能为空");
                            return 0;
                        }
                        if (sugar.empty(pwd)) {
                            alert("密码不能为空");
                            return 0;
                        }
                        sugar.call({
                            method: "post",
                            data: {
                                nickname: nick,
                                pwd: pwd
                            },
                            url: "//www.jamlib.com/api/login-manager/register",
                            type: "json",
                            cover: true,
                            withCookie: true,
                            success: function (json) {
                                if (json.code !== 200) {
                                    alert(json.message)
                                } else {
                                    alert("注册成功，请登陆～", 1000)
                                }
                            },
                            fail: function (json) {
                                alert("系统繁忙，请稍后再试～");
                                console.log(json);
                            }
                        })
                    });

                    sub.addEventListener("click", function(event) {
                        var nick = nickname.value;
                        var pwd = password.value;
                        if (sugar.empty(nick)) {
                            alert("用户名不能为空");
                            return 0;
                        }
                        if (sugar.empty(pwd)) {
                            alert("密码不能为空");
                            return 0;
                        }
                        sugar.call({
                            method: "post",
                            data: {
                                nickname: nick,
                                pwd: pwd
                            },
                            url: "//www.jamlib.com/api/login-manager/login",
                            type: "json",
                            cover: true,
                            withCookie: true,
                            success: function (json) {
                                if (json.code !== 200) {
                                    alert(json.message)
                                } else {
                                    config.success(json);
                                }
                            },
                            fail: function (json) {
                                alert("系统繁忙，请稍后再试～");
                                console.log(json);
                            }
                        })
                    });
                }
                this.active = function() {
                    node.style.display = "block";
                }
                this.hide = function() {
                    document.body.removeChild(node);
                }
                this.destroy = void(0);
            }
        }

        this.leave = function(ref) {
            this.setCookie("Token", null, -1);
            this.setCookie("Nickname", null, -1);
            this.setCookie("Coverid", null, -1);
            this.call({
                method: "get",
                url: "//www.jamlib.com/api/login-manager/leave",
                type: "json",
                cover: true,
                withCookie: true,
                success: function (json) {
                    if (json.code == 200) {
                        if (ref) {
                            location.reload(true);
                        }
                        console.log(document.cookie);
                    } else {
                        alert("系统繁忙，请稍后再试~");
                    }
                },
                fail: function (json) {
                    console.log(json);
                    alert("系统繁忙，请稍后再试～");
                }
            })
        }

        this.isJoin = function(success, fail) {
            if (this.empty(this.getCookie("Coverid"))) {
                alert("链接已过期，请刷新页面再试");
                return 0;
            }
            var nick = decodeURIComponent(this.getCookie("Nickname"));
            
            var json = {
                token: this.getCookie("Token"),
                nickname: nick,
                active: this.getCookie("Active"),
                unitid: this.getCookie("Unitid"),
            }
            let isJoin = (
                json.token != null &
                json.nickname != null &
                json.active != null &
                json.unitid != null
            ) == 0 ? false : true;
            if (isJoin) {
                success(json);
            } else {
                fail(json);
            }
        };

        /**
         * create or get node
         * normal is hide
         */
        this.need = function(name, config) {
            var idname = "sugar-tools-" + name;
            var node = document.getElementById(idname);
            if (node == null) {
                var tool = document.createElement("div");
                tool.id = idname
                let swap = new this.toolsFactory[name](tool, config);
                swap.create();
                swap.active();
                window.SugarTools[idname] = swap;
                return swap;
            } else {
                node.style.display = "block";
            }
        }
        
        this.query = function(name) {
            let reg = new RegExp("(^|&)"+ name+ "=([^&]*)(&|$)", "i");
            let swap = window.location.search.substr(1).match(reg);
            return (swap != null) ? unescape(swap[2]) : null;
        }

        this.getNode = function(nodeStr) {
            document.createTextNode
            return document.querySelectorAll(nodeStr);
        }
        this.createNode = function(nodeStr) {
            let nodeSign = nodeStr.substr(0, 1);
            let node = null;
            if (nodeSign === "#") {
                node = document.createElement("div");
                node.id = nodeStr.substr(1, nodeStr.length);
            } else if (nodeSign === ".") {
                node = document.createElement("div");
                node.className = nodeStr.substr(1, nodeStr.length);
            } else {
                node = document.createElement(nodeStr);
            }
            return node;
        }
        this.style = function(node, cssJson) {
            let key;
            let swap = "";
            for (key in cssJson) {
                swap += key+ ":"+ cssJson[key]+ ";";
            }
            node.style.cssText += ";"+ swap;
        }
    };

    window.alert = function(text, time) {
        var swap = "block";
        if (typeof (time) !== "undefined") {
            swap = "none";
        }
        var node = document.getElementById("sugar-tools-alert");
        if (node == null) {
            console.log(122)
            node = document.createElement("div");
            node.id = "sugar-tools-alert";
            var box = '<div id="sugar-alert" style="z-index:9999;">\
                            <div class="alert-nav">jamlib 提醒您</div>\
                            <div id="alert-text">'+text +'</div>\
                            <div id="alert-close" style="display:'+swap +';">确 定</div>\
                        </div>';
            node.innerHTML = box;
            document.body.appendChild(node);
            let ac = document.getElementById("alert-close");
            ac.addEventListener("click", function(event) {
                node.style.display = "none";
            });
            node.style.display = "block";
        }
        else {
            let at = document.getElementById("alert-text");
            let ac = document.getElementById("alert-close");
            if (typeof (time) !== "undefined") {
                ac.style.display = "none";
            } else {
                ac.style.display = "block";
            }
            at.innerText = text;
            node.style.display = "block";
        }
        if (typeof (time) !== "undefined") {
            setTimeout(function () {
                node.style.display = "none";
            }, time);
        }
    };
    window.$ = window.Sugar;
})();